<template>
    <div class="dashboard-container">
        <el-form ref="form" :rules="rules" :model="temp">
            <!-- 枚举名称 -->
            <h2>{{temp.systemFlag==1?"系统枚举：":""}}{{ temp.name }}</h2>
            <el-tree
                :data="data"
                node-key="id"
                default-expand-all
                :expand-on-click-node="false"
                :render-content="renderContent"
                style="margin-bottom: 10px;"
            >
            </el-tree>
            
            <!-- 操作按钮 -->
            <div>
                <el-button type="primary" @click="hanldeSubmit">确定</el-button>
                <el-button type="primary" plain @click="handleBack">返回</el-button>
            </div>
        </el-form>

        <!-- 新增列表 -->
        <el-dialog 
            :title="dialogType=='create'?'新增列':'编辑列'"
            :visible.sync="dialogVisible" 
            :close-on-click-modal="false"
            @close="dialogVisible=false"
            width="600px"
        >
            <el-form ref="form" :rules="rules" :model="titlesTemp">
                <el-form-item label="列名">
                    <el-input v-model="titlesTemp.name" placeholder="请输入列名"></el-input>
                </el-form-item>
                <el-form-item label="单位">
                    <el-input v-model="titlesTemp.valueUnit" placeholder="请输入单位"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submit('form')">提交</el-button>
                    <el-button @click="dialogVisible = false">取消</el-button>
                </el-form-item>
            </el-form>
            
        </el-dialog>
    </div>
</template>
  
<script>
import { mapGetters } from 'vuex'
import { enumInfo, enumUpdate, enumCreate } from '@/api/enum'
import { TARGET_TYPE_LIST } from '@/utils/common'

let id = 0;
export default {
    name: 'StaffEnumAdd',
    computed: {
      ...mapGetters([
        'name'
      ])
    },
    data(){
      return {
        data: [],
        TARGET_TYPE_LIST,
        rules: {
            name: [{ required: true, message: '请输入列名', trigger: 'blur' }],
            valueUnit: [{ required: true, message: '请输入单位', trigger: 'blur' }],
        },
        id: '',
        temp: {
            name: '',
            propertyType: '',
            items: [],
            titles: [],
            provinceId: '',
            cityId: '',
            areaId: '',
            streeId: '',
            objectType: 3
        },
        titlesTemp: {
            name: '',
            valueUnit: ''
        },
        dialogVisible: false, 
        dialogType: 'create',
      }
    },
    mounted(){
        this.id = this.$router.history.current.query.id;
        if(this.id){
            this.getInfo();
        }
    },
  
    methods:{
        append(data) {
            const newChild = { id: id++, label: 'testtest', children: [] };
            if (!data.children) {
            this.$set(data, 'children', []);
            }
            data.children.push(newChild);
        },

        remove(node, data) {
            const parent = node.parent;
            const children = parent.data.children || parent.data;
            const index = children.findIndex(d => d.id === data.id);
            children.splice(index, 1);
        },

        renderContent(h, { node, data, store }) {
            return (
            <span class="custom-tree-node">
                <span>{node.label}</span>
                <span>
                <el-button size="mini" type="text" style="margin-left: 10px;" on-click={ () => this.append(data) }>新增</el-button>
                <el-button size="mini" type="text" on-click={ () => this.remove(node, data) }>删除</el-button>
                </span>
            </span>);
        },
        //删除列
        handleDeleteCol(name){
            this.temp.items = this.temp.items.map(item=>{
                item.values.forEach((value,vIndex)=>{
                    if(value.enumTitleName==name){
                        item.values.splice(vIndex, 1)
                    }
                })
                return item;
            })
            this.temp.titles = this.temp.titles.filter(item=>item.name!=name)
        },
        // 提交修改
        async hanldeSubmit(){
            let temp = JSON.parse(JSON.stringify(this.temp));
            if(this.id){
                let { id, items, titles } = temp;
                await enumUpdate({ id, items, titles })
                this.$message.success({ message: '修改成功' })
                this.handleBack();
            }else{ 
                await enumCreate(temp)
                this.$message.success({ message: '创建成功' })
                this.handleBack();
            }
        },
        handleBack(){
            this.$router.history.push({ path: '/data/enum' });
        },
        // 删除行
        handleDeleteRow(index){
            this.temp.items.splice(index, 1)
        },
        // 添加行
        handleAddRow(){
           let values = this.temp.titles.concat().map(item=>{
                return { enumTitleName: item.name, value: '' }
           })
           this.temp.items.push({
                name: '',
                description: '',
                values
           }) 
        },
        //提交表单
        submit(formName){
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    if(this.dialogType =='create'){
                        // 添加逻辑....
                        this.temp.items = this.temp.items.map(item=>{
                            item.values.push({
                                enumTitleName: this.titlesTemp.name,
                                value: ''
                            })
                            return item;
                        })
                        this.temp.titles.push(this.titlesTemp)
                        this.$message.success('创建成功')

                    }else{
                        //修改逻辑....
                        this.$message.success('修改成功')
                    }
                    this.dialogVisible = false;
                }else {
                    console.log('error submit!!');
                    return false;
                }
            });         
        },
        //点击新增、编辑
        handleAdd(type, row){
            //判断如果一行数据都没有，则不让新增列
            if(this.temp.items.length==0){
                    this.$message.error({ message: '请新增行' })
                    return;
            }
            this.dialogType = type;
            this.dialogVisible = true;
            if(type=='create'){
                this.titlesTemp = {
                    name: '',
                    valueUnit: ''
                }
            }else{
                this.titlesTemp = row
            }
        },
        async getInfo(){
            let data = await enumInfo({id: this.id  });
            let { id, name, propertyType, items, titles, systemFlag } = data
            
            items = items.map(item=>{
                return { label: item.name, id: item.id, description: item.description, values: item.values, level: item.level, children: [], parentId: item.parentId }
            })
            titles = titles.map(item=>{
                return { name: item.name, id: item.id, valueUnit: item.valueUnit }
            })
            this.temp = {
                id, name, propertyType, items, titles,systemFlag
            };
            // id， label children
            this.data = [];
            for(let i = 1; i<10; i++){
                let arr = items.filter(item=>item.level==i);
                // 遇到这个层级没有数据的，直接跳出
                if(arr.length==0)break;
                console.log(arr)
                //循环这个层级;
                arr.forEach(aItem=>{
                    if(i==1){
                        this.data.push(aItem)
                    }else{
                        this.data = this.data.map(dItem=>{
                            console.log(dItem.id==aItem.parentId)
                            if(dItem.id==aItem.parentId){
                                dItem.children.push(aItem)
                            }
                            return dItem;
                        })
                    }
                })
            }
            console.log(this.data)
        }
    }
}
</script>
  
<style lang="scss" scoped>
.dashboard {
    &-container {
      margin: 30px;
      position: relative;
      .right{
        position: absolute;
        right: 0;
        top: 0;
      }

      .page{
        padding: 20px 0;
        text-align: center;
      }
    }
    &-text {
      font-size: 30px;
      line-height: 46px;
    }
}
</style>
  